package com.xiaofengstu.mcams.web.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaofengstu.mcams.annotation.ILog;
import com.xiaofengstu.mcams.constant.ApiConstants;
import com.xiaofengstu.mcams.constant.SysConstants;
import com.xiaofengstu.mcams.dto.BasicResultDTO;
import com.xiaofengstu.mcams.dto.UserDTO;
import com.xiaofengstu.mcams.enums.RespStatusEnum;
import com.xiaofengstu.mcams.util.JwtUtils;
import com.xiaofengstu.mcams.util.Md5Utils;
import com.xiaofengstu.mcams.util.RedisUtils;
import com.xiaofengstu.mcams.util.ThreadLocalUtils;
import com.xiaofengstu.mcams.web.entity.TUser;
import com.xiaofengstu.mcams.web.service.TUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author fengzeng
 * @since 2022-05-07
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/web/user")
public class TUserController {

  private final TUserService userService;
  private final RedisUtils redisUtil;
  private final JwtUtils jwtUtil;

  private final Md5Utils md5Utils;

  @RequestMapping(value = ApiConstants.LOGIN, method = RequestMethod.POST)
  public BasicResultDTO<String> login(@RequestBody UserDTO userDTO) {
    if (userDTO.getUsername() == null) {
      return new BasicResultDTO<>(RespStatusEnum.FAIL, SysConstants.USERNAME_OR_PASSWORD_ERROR);
    }

    QueryWrapper<TUser> qw = new QueryWrapper<>();
    qw.eq("username", userDTO.getUsername());
    // 校验密码
    TUser user = userService.getOne(qw);
    String salt = user.getSalt();
    String md5Password = md5Utils.getMd5Password(userDTO.getPassword(), salt);

    if (!user.getPassword().equals(md5Password)) {
      return new BasicResultDTO<>(RespStatusEnum.FAIL, SysConstants.USERNAME_OR_PASSWORD_ERROR);
    }

    // 生成 token
    String token = jwtUtil.getToken(user.getUserId());

    // 设置 redis 缓存时间，单位秒
    long expire = SysConstants.HALF_HOUR;
    if (Boolean.TRUE.equals(userDTO.getIsRememberMe())) {
      expire = SysConstants.ONE_DAY;
    }
    redisUtil.cacheValue(String.valueOf(user.getUserId()), token, expire);

    return new BasicResultDTO<>(RespStatusEnum.SUCCESS, token);
  }


  @ILog("获取用户列表")
  @GetMapping("/list")
  public BasicResultDTO<Page<UserDTO>> getUserList(@RequestParam("page") Integer page, @RequestParam("size") Integer size) {
    return new BasicResultDTO<>(RespStatusEnum.SUCCESS, userService.getUserList(page, size));
  }

  @ILog("条件查询用户")
  @GetMapping("/search")
  public BasicResultDTO<List<UserDTO>> search(@RequestParam(value = "username", required = false) String username,
                                              @RequestParam(value = "campusId", required = false) Integer campusId,
                                              @RequestParam(value = "deptId", required = false) Integer deptId) {
    return new BasicResultDTO<>(RespStatusEnum.SUCCESS, userService.searchBy(username, campusId, deptId));
  }

  @ILog("新增用户")
  @PostMapping("/add")
  public BasicResultDTO<Boolean> add(@RequestBody() TUser user) {
    user.setSuperiorUid(ThreadLocalUtils.get());
    String salt = UUID.randomUUID().toString();
    String md5Password = md5Utils.getMd5Password(user.getPassword(), salt);
    user.setPassword(md5Password);
    user.setSalt(salt);
    return new BasicResultDTO<>(RespStatusEnum.SUCCESS, userService.save(user));
  }

  @ILog("更新用户信息")
  @PostMapping("/update")
  public BasicResultDTO<Boolean> updateById(@RequestBody TUser user) {
    user.setSuperiorUid(ThreadLocalUtils.get());
    String s = "1cs";
    return new BasicResultDTO<>(RespStatusEnum.SUCCESS, userService.update(user, new QueryWrapper<TUser>().eq("user_id", user.getUserId())));
  }

  @ILog("删除用户")
  @PostMapping("/del")
  public BasicResultDTO<Boolean> delById(@RequestBody Integer userId) {
    return new BasicResultDTO<>(RespStatusEnum.SUCCESS, userService.removeById(userId));
  }
}
